package com.ekuaitu.kuaitustaff.utils.ble.utils;

public class ConvertHelper {

    public static String byteArrayToHexString(byte[] bs, int start, int length) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++)
            sb.append(byteToHexString(bs[start + i]));

        return sb.toString();
    }

    public static String byteArrayToHexString(byte[] bs) {
        return byteArrayToHexString(bs, false);
    }

    public static String byteArrayToHexString(byte[] bs, boolean isSpace) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bs)
            sb.append(byteToHexString(b)).append(isSpace ? " " : "");

        return sb.toString();
    }

    public static String byteToHexString(byte b) {
        String str = Integer.toHexString(b & 0xff);
        if (str.length() < 2)
            return "0" + str;
        else
            return str.substring(str.length() - 2);
    }

//	public static byte[] hexStringToByteArray(String hex)
//	{
//		byte[] stbs = new byte[hex.length() / 2];
//		for (int i = 0; i < hex.length() / 2; i++)
//		{
//			stbs[i] = Byte.valueOf(hex.substring(i * 2, i * 2 + 2), 16);
//		}
//		return stbs;
//	}

    public static byte[] hexStringToByteArray(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static int bytesToInt(byte b1, byte b2) {
        return bytesToInt((byte) 0, (byte) 0, b1, b2);
    }

    public static int bytesToInt(byte b1, byte b2, byte b3) {
        return bytesToInt((byte) 0, b1, b2, b3);
    }

    public static int bytesToInt(byte b1, byte b2, byte b3, byte b4) {
        int u = ((b4 & 0xff) | (b3 & 0xff) << 8 | (b2 & 0xff) << 16 | (b1 & 0xff) << 24);
        return u;
    }

    public static byte[] intToByte(int number) {
        int temp = number;
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            b[3 - i] = (byte) (temp & 0xff);
            temp = temp >> 8;
        }
        return b;
    }

}
